package com.gdssoft.pdaweb.action.water;

import java.text.ParseException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.annotation.Resource;
import com.gdssoft.core.command.QueryFilter;
import com.gdssoft.core.util.BeanUtil;
import com.gdssoft.core.util.ContextUtil;
import com.gdssoft.core.util.JsonUtil;
import com.gdssoft.core.web.action.BaseAction;
import com.gdssoft.framework.model.system.AppUser;
import com.gdssoft.framework.model.system.Department;
import com.gdssoft.framework.service.system.DepartmentService;
import com.gdssoft.pdaweb.model.AutoPlan;
import com.gdssoft.pdaweb.model.PdaMdBuilding;
import com.gdssoft.pdaweb.model.PdaMdDistrict;
import com.gdssoft.pdaweb.model.PdaMdHouse;
import com.gdssoft.pdaweb.model.PdaPlanDetail;
import com.gdssoft.pdaweb.model.water.PdaWaterMeter;
import com.gdssoft.pdaweb.model.water.WaterMeterMonthPlanRead;
import com.gdssoft.pdaweb.model.water.WaterMeterPlan;
import com.gdssoft.pdaweb.service.AutoPlanService;
import com.gdssoft.pdaweb.service.PdaMdBuildingService;
import com.gdssoft.pdaweb.service.PdaMdDistrictService;
import com.gdssoft.pdaweb.service.PdaMdHouseService;
import com.gdssoft.pdaweb.service.PdaPlanDetailService;
import com.gdssoft.pdaweb.service.water.PdaWaterMeterService;
import com.gdssoft.pdaweb.service.water.WaterMeterMonthPlanService;
import com.gdssoft.pdaweb.service.water.WaterMeterPlanService;
import com.ibm.icu.text.SimpleDateFormat;

import flexjson.JSONSerializer;
import flexjson.transformer.DateTransformer;

public class WaterMeterPlanAction extends BaseAction {
	@Resource
	private WaterMeterPlanService waterMeterPlanService;

	@Resource
	private WaterMeterMonthPlanService waterMeterMonthPlanService;

	@Resource
	private PdaWaterMeterService pdaWaterMeterService;

	@Resource
	private PdaMdDistrictService pdaMdDistrictService;

	@Resource
	private PdaMdBuildingService pdaMdBuildingService;
	
	@Resource
	private PdaMdHouseService pdaMdHouseService;
	
	@Resource
	private AutoPlanService autoPlanService;
	
	
	@Resource
	private DepartmentService departmentService;
	@Resource
	private PdaPlanDetailService pdaPlanDetailService;
	private WaterMeterPlan waterMeterPlan;

	private Long planId;

	public PdaMdBuildingService getPdaMdBuildingService() {
		return pdaMdBuildingService;
	}

	public void setPdaMdBuildingService(
			PdaMdBuildingService pdaMdBuildingService) {
		this.pdaMdBuildingService = pdaMdBuildingService;
	}

	public PdaMdDistrictService getPdaMdDistrictService() {
		return pdaMdDistrictService;
	}

	public void setPdaMdDistrictService(
			PdaMdDistrictService pdaMdDistrictService) {
		this.pdaMdDistrictService = pdaMdDistrictService;
	}

	public PdaWaterMeterService getPdaWaterMeterService() {
		return pdaWaterMeterService;
	}

	public void setPdaWaterMeterService(
			PdaWaterMeterService pdaWaterMeterService) {
		this.pdaWaterMeterService = pdaWaterMeterService;
	}

	public WaterMeterMonthPlanService getWaterMeterMonthPlanService() {
		return waterMeterMonthPlanService;
	}

	public void setWaterMeterMonthPlanService(
			WaterMeterMonthPlanService waterMeterMonthPlanService) {
		this.waterMeterMonthPlanService = waterMeterMonthPlanService;
	}

	public WaterMeterPlanService getWaterMeterPlanService() {
		return waterMeterPlanService;
	}

	public void setWaterMeterPlanService(
			WaterMeterPlanService waterMeterPlanService) {
		this.waterMeterPlanService = waterMeterPlanService;
	}

	public WaterMeterPlan getWaterMeterPlan() {
		return waterMeterPlan;
	}

	public void setWaterMeterPlan(WaterMeterPlan waterMeterPlan) {
		this.waterMeterPlan = waterMeterPlan;
	}

	public Long getPlanId() {
		return planId;
	}

	public void setPlanId(Long planId) {
		this.planId = planId;
	}

	/**
	 * 显示列表
	 */
	public String list() {
		QueryFilter filter = new QueryFilter(getRequest());
		filter.addSorted("planStatus", QueryFilter.ORDER_DESC);
		filter.addSorted("planName", QueryFilter.ORDER_ASC);
		filter.addFilter("Q_department.depId_S_LIN", getSubOfficeIds());//只查当前用户权限下的管理处
		List<WaterMeterPlan> list = waterMeterPlanService.getAll(filter);
		
//		int toDayDate = Calendar.getInstance().get(Calendar.DATE);
//		String thisMonth = DateUtil.dateFormat(new Date(), "yyyy-MM");
//		WaterMeterMonthPlan monthPlan = null;
		/*for(WaterMeterPlan p :list){
			if(toDayDate > Integer.parseInt(p.getAccountDay())){	//过了月结日
				p.setPlanStatus(0L);
			}else{
				monthPlan = waterMeterMonthPlanService.getByPlanIdAndMonth(p.getPlanId(),thisMonth);
				if(monthPlan != null && monthPlan.getPlanStatus()==0L){
					//当状态是执行过的，设置为2
					p.setPlanStatus(2L);
				}
			}
		}*/
		
		JSONSerializer serializer=new JSONSerializer();
		
		StringBuffer buff = new StringBuffer("{success:true,'totalCounts':")
		.append(filter.getPagingBean().getTotalItems()).append(",result:");	
		serializer.transform(new DateTransformer("yyyy-MM-dd"), "createddt");
		serializer.transform(new DateTransformer("yyyy-MM-dd"), "lastEditDt");
        buff.append(serializer.exclude(new String[] { "class" }).serialize(list));
		buff.append("}");
		
		jsonString = buff.toString();
		System.out.print(jsonString);

		return SUCCESS;
	}
	


	/**
	 * 批量删除
	 * 
	 * @return
	 */

	public String multiDel() {

		String[] ids = getRequest().getParameterValues("ids");
		if (ids != null) {
			for (String id : ids) {
				try {
					this.waterMeterPlanService.remove(new Long(id));
				} catch (NumberFormatException e) {
					e.printStackTrace();
				} catch (Exception e) {
					e.printStackTrace();
				}

			}
		}
		jsonString = "{success:true}";
		return SUCCESS;
	}

	/**
	 * 显示详细信息
	 * 
	 * @return
	 */
	public String get() {
		// deviceId =
		// Long.parseLong(getRequest().getParameterValues("deviceId")[0]);
		// DeviceReg deviceReg=deviceRegService.get(deviceId);
		// //Gson gson = new
		// GsonBuilder().excludeFieldsWithoutExposeAnnotation().setDateFormat("yyyy-MM-dd").create();
		// Gson gson = new
		// GsonBuilder().excludeFieldsWithoutExposeAnnotation().create();
		// //将数据转成JSON格式
		// StringBuffer sb = new StringBuffer("{success:true,data:");
		// sb.append(gson.toJson(deviceReg));
		// sb.append("}");
		//
		// setJsonString(sb.toString());
		return SUCCESS;
	}
	
	public String getDetail() {
		Long planId = Long.parseLong(getRequest().getParameter("planId"));
		AutoPlan autoPlan = autoPlanService.getWaterOpenAutoPlan(planId);
		
		JSONSerializer json = new JSONSerializer();
		StringBuffer buff = new StringBuffer("{success:true,totalCounts:1,data:");
		json.transform(new DateTransformer("yyyy-MM-dd"), "beginTime");
		json.transform(new DateTransformer("yyyy-MM-dd"), "endTime");
		json.transform(new DateTransformer("yyyy-MM-dd"), "executeDate");
		buff.append(json.exclude(new String[] { "class" }).serialize(autoPlan));
		buff.append("}");
		setJsonString(buff.toString());
		return SUCCESS;
	}

	/**
	 * 添加及保存操作
	 */
	public String save() {
		
		String removedStr = getRequest().getParameter("removed");
		String[] removeds = {};
		if(!removedStr.trim().isEmpty()){
			removeds = removedStr.split(",");
		}		
		String amIdss = getRequest().getParameter("selectedIds");
		String[] amIds = {};
		if(!amIdss.trim().isEmpty()){
			amIds = amIdss.split(",");
		}
		
		logger.info("要保存的该计划中的水表id------" + amIds);
		boolean success = true;
		if (amIds.length == 0) {
			success = false;
			logger.info("该计划中无水表返回保存失败");
		} else {
			String un = ContextUtil.getCurrentUser().getUsername();
			Date now = new Date();
			if (waterMeterPlan.getPlanId() == null) {
				waterMeterPlan.setCreatedby(un);
				waterMeterPlan.setCreateddt(now);
				waterMeterPlan.setPlanStatus((long) 0);
				waterMeterPlan.setIsAutoPlan(0);
			}else{
				WaterMeterPlan plan = waterMeterPlanService.get(waterMeterPlan
						.getPlanId());
				try {
					BeanUtil.copyNotNullProperties(plan, waterMeterPlan);
				} catch (Exception e) {
					success = false;
					logger.info("将一个bean中的非空属性拷贝到另一个bean时出现错误");
					e.printStackTrace();
				}
				waterMeterPlan = plan;
				waterMeterPlan.setLastEditDt(now);
				waterMeterPlan.setLastEditBy(un);
			}
			waterMeterPlan.setMeterCount(new Long(amIds.length));
			logger.info("该计划中添加了多少个水表----:" + amIds.length);
			try {
				waterMeterPlanService.save(waterMeterPlan, amIds, removeds);
			} catch (Exception e) {
				success = false;
				logger.debug("保存失败----:" + e.getMessage());
				e.printStackTrace();
			}
		}
		setJsonString("{success:" + success + "}");
		return SUCCESS;
	}

	//检测计划所抄表的年月是否已经存在于数据库中
	public String check(){
		String planId = getRequest().getParameter("planId");
		String beginTime = getRequest().getParameter("beginTime");
		String endTime = getRequest().getParameter("endTime");
		String accountDay = getRequest().getParameter("accountDay");
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		Date beginTime2 = new Date();
		Date endTime2 = new Date();
		
		try {
			beginTime2 = sdf.parse(beginTime);
			endTime2 = sdf.parse(endTime);
		} catch (ParseException e) {
			logger.debug("日期转换出错,beginTime:" + beginTime + ",endTime:"
					+ endTime);
			e.printStackTrace();
		}
//		String month = waterMeterPlanService.getThisMonth(Integer.parseInt(accountDay), beginTime2, endTime2);
		String month = new SimpleDateFormat("yyyy-MM").format(beginTime);
		Boolean result = waterMeterPlanService.check(Long.parseLong(planId), month);
		jsonString = "{success:true,date:{\"result\":\"" + result + "\"}}";
		return SUCCESS;
	}
	/**
	 * 执行计划变更
	 */
	public String executeAlter() {
		String username = getRequest().getParameter("username");
		String planId = getRequest().getParameter("planId");
		String beginTime = getRequest().getParameter("beginTime");
		String endTime = getRequest().getParameter("endTime");
		Integer isAutoPlan = getRequest().getParameter("isAutoPlan")==null?0:1;
		
		String un = ContextUtil.getCurrentUser().getUsername();
				
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		Date beginTime2 = new Date();
		Date endTime2 = new Date();
		
		try {
			beginTime2 = sdf.parse(beginTime);
			endTime2 = sdf.parse(endTime);
		} catch (ParseException e) {
			logger.debug("日期转换出错,beginTime:" + beginTime + ",endTime:"
					+ endTime);
			e.printStackTrace();
		}
		WaterMeterPlan waterMeterPlan = waterMeterPlanService.get(Long.parseLong(planId));
		waterMeterPlan.setIsAutoPlan(isAutoPlan);
		try {
			waterMeterPlanService.save(waterMeterPlan);
		} catch (Exception e1) {
			e1.printStackTrace();
		}
		
		AutoPlan autoPlan = autoPlanService.getWaterOpenAutoPlan(Long.parseLong(planId));
		if(isAutoPlan != 1){
			try {
				jsonString = "{success:" + autoPlanService.remove(autoPlan.getId()) + "}"; 
			} catch (Exception e) {
				e.printStackTrace();
			}
		}else{
			autoPlan.setExecutor(username);
			autoPlan.setBeginTime(beginTime2);
			autoPlan.setEndTime(endTime2);
			autoPlan.setLastEditBy(un);
			autoPlan.setLastEditDt(new Date());
			try {
				jsonString = "{success:" + (autoPlanService.save(autoPlan)!=null) + "}";
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		
	
		return SUCCESS;
	}
	
	/**
	 * 执行计划
	 */
	public String execute() {
		String username = getRequest().getParameter("username");
		String planId = getRequest().getParameter("planId");
		String beginTime = getRequest().getParameter("beginTime");
		String endTime = getRequest().getParameter("endTime");
		Integer isAutoPlan = getRequest().getParameter("isAutoPlan")==null?0:1;
		String un = ContextUtil.getCurrentUser().getUsername();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		Date beginTime2 = new Date();
		Date endTime2 = new Date();
		try {
			beginTime2 = sdf.parse(beginTime);
			endTime2 = sdf.parse(endTime);
		} catch (ParseException e) {
			logger.debug("日期转换出错,beginTime:" + beginTime + ",endTime:"
					+ endTime);
			e.printStackTrace();
		}
		
		boolean res = waterMeterPlanService.execute(Long.parseLong(planId),
				beginTime2, endTime2, username);
		
		//执行成功后
		if(res){
			//更新总计划表自动执行标志位
			WaterMeterPlan waterMeterPlan = waterMeterPlanService.get(Long.parseLong(planId));
			waterMeterPlan.setIsAutoPlan(isAutoPlan);
			try {
				waterMeterPlanService.save(waterMeterPlan);
			} catch (Exception e1) {
				e1.printStackTrace();
			}
			if(isAutoPlan == 1){ //如果自动执行将数据插入自动执行表
				AutoPlan nextAutoPlan = new AutoPlan(Long.parseLong(planId), 
											AutoPlan.TYPE_WATER,beginTime2, 
											endTime2, username,un).nextMonthAutoPlan(un);
				
				nextAutoPlan.setCreateddt(new Date());
				try {
					autoPlanService.save(nextAutoPlan);
				} catch (Exception e) {
					e.printStackTrace();
				}
				
			}
			
		}
		
		jsonString = "{success:" + res + "}";

		return SUCCESS;
	}

	/**
	 * 显示抄表人姓名
	 * 只能查到该计划所属部门的抄表员
	 */
	public String showExecutorName() {
		Long depId = waterMeterPlanService.get(planId).getDepartment().getDepId();
		List<AppUser> ls = waterMeterPlanService.getExecutor(depId.toString());
//		QueryFilter filter = new QueryFilter(getRequest());
//		filter.addFilter("Q_employee.department.depId_S_LIN", getSubOfficeIds());
//		filter.addFilter("Q_roles.roleCode_S_EQ", "ROLE_WATER_READING"); //roleCode=ROLE_WATER_READING:水表抄表员
//		List<AppUser> ls = appUserService.getAll(filter);
//		filter.addFilter("Q_department.depId_S_LIN", getSubOfficeIds());
//		filter.addFilter("Q_roles.roleCode_S_EQ", "ROLE_WATER_READING"); //roleCode=ROLE_WATER_READING:水表抄表员
//		List<Employee> ls = employeeService.getAll(filter);
//		if(ls.size()>0){
//			AppUser appUser = (AppUser)ls.get(0).getAppUsers().iterator().next();
//		}
		
		StringBuffer buff = new StringBuffer("[");
		if(ls.size()>0){
			for (AppUser appUser : ls) {
				buff.append("[\"" + appUser.getUsername() + "\",\""
						+ appUser.getFullname() + "(" + appUser.getUsername()
						+ ")\"],");
			}
			buff.deleteCharAt(buff.length() - 1);
		}
		buff.append("]");

		setJsonString(buff.toString());

		return SUCCESS;
	}

	/**
	 * 通过Id获取相应的水表号
	 */
	public String getByPlanId() {
		List<String> amIds = waterMeterPlanService.getByPlanId(planId);
		StringBuffer buff = new StringBuffer("[");
		for (String id : amIds) {
			buff.append("[\"" + id + "\",\"" + id + "\"],");
		}
		buff.deleteCharAt(buff.length() - 1);
		buff.append("]");
		setJsonString(buff.toString());

		return SUCCESS;
	}

	/**
	 * 显示水表编号（属于当前用户所管辖范围内指定区、栋的水表）
	 * @author F3229233
	 */
	public String getWaterMeterId() {
		String districtId = getRequest().getParameter("districtId");
		String buildingId = getRequest().getParameter("buildingId");

		//List<PdaWaterMeter> ls = pdaWaterMeterService.getWaterMeter(districtId,buildingId);
		QueryFilter filter = new QueryFilter(0,Integer.MAX_VALUE);
		filter.addFilter("Q_districtId_S_EQ", districtId);
		if(!buildingId.isEmpty()){	//栋可以为空
			filter.addFilter("Q_buildingId_S_EQ", buildingId);
		}
		filter.addFilter("Q_department.depId_S_LIN", getSubOfficeIds());
		filter.addFilter("Q_type_S_EQ", "2");
		filter.addSorted("position", "asc");
		List<PdaWaterMeter> ls = pdaWaterMeterService.getAll(filter);
		
		List<PdaWaterMeter> tempList= new ArrayList<PdaWaterMeter>();
		QueryFilter filter1 = new QueryFilter();
		filter1.addFilter("Q_type_N_EQ", String.valueOf(PdaPlanDetail.WATER));
		List<PdaPlanDetail> ppdList = pdaPlanDetailService.getAll(filter1);
		for(PdaPlanDetail ppd:ppdList){
			for(PdaWaterMeter pwm:ls){
				if(pwm.getAmId().equals(ppd.getMeterId())){
					tempList.add(pwm);
				}
			}
		}
		for(PdaWaterMeter temp:tempList){
				ls.remove(temp);
		}
		
		if (ls.size() > 0) {
			StringBuffer buff = new StringBuffer("[");
			for (PdaWaterMeter pdaWaterMeter : ls) {
				buff.append("[\"" + pdaWaterMeter.getAmId() + "\",\"【"
						+ pdaWaterMeter.getAmId() + "】"
						+ pdaWaterMeter.getPosition() + "\"],");
			}
			buff.deleteCharAt(buff.length() - 1);
			buff.append("]");
			setJsonString(buff.toString());
		} else {
			setJsonString("[]");
		}
		return SUCCESS;
	}

	/**
	 * 获取当前用户下属的未删除所有管理处的id
	 * @return 如"101,12,15"
	 */
	private String getSubOfficeIds() {
		String depIds = "";
		QueryFilter filter = new QueryFilter(0,Integer.MAX_VALUE);
		filter.addFilter("Q_depLevel_N_EQ", "2");//'0:保留，1:公司，2:管理处'
		filter.addFilter("Q_path_S_LFK", ContextUtil.getCurrentUser().getEmployee().getDepartment().getPath());
		List<Department> list = departmentService.getAll(filter);
		if(list.size()>0){
			for (Department department : list) {
				depIds += department.getDepId()+",";		
			}
			depIds = depIds.substring(0, depIds.length()-1);
		}
		return depIds;
	}

	/**
	 * 右边栏过滤
	 * @return
	 */
	public String getSelectWaterMeterId(){
		String districtId = getRequest().getParameter("districtId");
		String ids = getRequest().getParameter("ids");
		String[] amIds = {};
		if(!ids.trim().isEmpty()){
			amIds = ids.split(",");
		}
		List<PdaWaterMeter> ls = pdaWaterMeterService.getSelectWaterMeter(districtId, amIds);
		if(ls.size() > 0){
			StringBuffer buff = new StringBuffer("[");
			for (PdaWaterMeter pdaWaterMeter : ls) {
				buff.append("[\"" + pdaWaterMeter.getAmId() + "\",\""
						+ pdaWaterMeter.getAmId() + "\"],");
			}
			buff.deleteCharAt(buff.length() - 1);
			buff.append("]");
			setJsonString(buff.toString());
		}else {
			setJsonString("[]");
		}
		return SUCCESS;
	}
	/**
	 * 查看任务
	 */
	public String checkTask() {
		// SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");

		String planId = getRequest().getParameter("planId");
		String month = getRequest().getParameter("month");

		List<WaterMeterMonthPlanRead> ls = waterMeterPlanService.getPlanTask(
				Long.parseLong(planId), month);

		StringBuffer buff = new StringBuffer("{success:true,'result':");

		JSONSerializer json = JsonUtil.getJSONSerializer();
		buff.append(json.exclude(
				new String[] { "class", "WaterMeterMonthPlanRead" }).serialize(
				ls));
		buff.append("}");

		jsonString = buff.toString();
		return SUCCESS;
	}

	/**
	 * 显示区号信息,返回当前用户下属的区列表
	 * 关系：officeCode-->department.code
	 */
	public String showDistrict() {
		String codes = departmentService.getSubDepCodes();
		if(codes.isEmpty()){
			setJsonString("[]");
		}else{
			QueryFilter filter = new QueryFilter(0,Integer.MAX_VALUE);
			filter.addFilter("Q_officeCode_S_SIN", codes);
			List<PdaMdDistrict> ls = pdaMdDistrictService.getAll(filter);
			StringBuffer buff = new StringBuffer("[");
			if(ls.size() > 0){
				for (PdaMdDistrict pdaMdDistrict : ls) {
					buff.append("[\"" + pdaMdDistrict.getDistrictId() + "\",\""
							+ pdaMdDistrict.getDistrictName() + "\"],");
				}
				buff.deleteCharAt(buff.length() - 1);
			}
			buff.append("]");

			setJsonString(buff.toString());
		}
		
		return SUCCESS;
	}

	/**
	 * 显示栋号信息
	 */
	public String showBuilding() {
		String districtId = getRequest().getParameter("districtId");
		List<PdaMdBuilding> ls = pdaMdBuildingService
				.getByDistrictId(districtId);

		StringBuffer buff = new StringBuffer("[");
		if(ls.size() > 0){
			for (PdaMdBuilding pdaMdBuilding : ls) {
				buff.append("[\"" + pdaMdBuilding.getBuildingId() + "\",\""
						+ pdaMdBuilding.getBuildingName() + "\"],");
			}
			buff.deleteCharAt(buff.length() - 1);
		}
		buff.append("]");

		setJsonString(buff.toString());

		return SUCCESS;
	}
	
	/**
	 * 显示房间信息
	 */
	public String showHouse() {
		String buildingId = getRequest().getParameter("buildingId");
		QueryFilter filter = new QueryFilter(0,Integer.MAX_VALUE);
		filter.addFilter("Q_buildingId_S_EQ", buildingId);
		filter.addSorted("name", "asc");
		List<PdaMdHouse> ls = pdaMdHouseService.getAll(filter);
		StringBuffer buff = new StringBuffer("[");
		if(ls.size() > 0){
			for (PdaMdHouse pdaMdHouse : ls) {
				buff.append("[\"" + pdaMdHouse.getHouseId() + "\",\""
						+ pdaMdHouse.getName()+ "\",\""
						+ pdaMdHouse.getOwner()+ "\"],");
			}
			buff.deleteCharAt(buff.length() - 1);
		}
		buff.append("]");

		setJsonString(buff.toString());

		return SUCCESS;
	}

}
